<?php
// 设置响应头，指定返回JSON数据
header('Content-Type: application/json;charset=utf-8');
// 获取原始POST数据
$string = json_decode(file_get_contents('php://input'),true);

$txtPath="../../datas/txt/";
$filePath="../../datas/file/";

//使用单例模式解决多次实例化sqlite3的问题
class Database {
    private static ?SQLite3 $instance = null;
    private string $dbPath;

    private function __construct(string $dbPath) {
        $this->dbPath = $dbPath;
        self::$instance = new SQLite3($dbPath);
        self::$instance->exec('PRAGMA busy_timeout = 5000'); // 设置5秒超时
    }

    public static function getInstance(string $dbPath): SQLite3 {
        if (self::$instance === null) {
            new self($dbPath);
        }
        return self::$instance;
    }

    // 防止克隆实例
    private function __clone() {}

    // 防止反序列化实例
    private function __wakeup() {}
}

$db=Database::getInstance("../../datas/data.db");




//数据注册所有功能在这里实现
register();
function  register()
{
   global $string;
 //保存
   if($string["flag"]=="saveText")
   {
      echo save($string["cls"],$string["title"],
         $string["data"],$string["fileName"],
         $string["changFlag"],$string["oldCls"],
         $string["oldTitle"],$string["noCheckSave"]);
  }

    //上传文件
  $formDate=$_REQUEST;
  if($formDate['flag']=="upload")
  {
      echo upload($formDate);
  }

  //模糊查找文件
  if($string["flag"]=="findFile")
  {
      echo findFile($string["searchValue"]);
  }

 //点击工具栏中的类进行显示名称
  if($string["flag"]=="getCls")
  {
      echo showAllTitle($string["cls"]);
  }

  //显示工具栏前n个数据
  if($string["flag"]=="getToolCls")
  {
      echo getToolCls($string["count"]);
  }

 //显示工具栏前n个数据
  if($string["flag"]=="getInitData")
  {
      echo getInitData($string["count"]);
  }
 //获取所有的类
  if($string["flag"]=="getAllCls")
  {   
      echo getAllCls();
  }

  //删除数据
  if($string["flag"]=="dele")
  {   
      echo  deleData($string["title"],$string["cls"]);
  }




}





//保存函数
function  save($cls,$title,$data,$fileList,$changFlag,$oldCls,$oldTitle,$noCheckSave)
{   
   global $txtPath,$filePath;

   $newFiles="";
   if(($cls!=$oldCls||$title!=$oldTitle)&&$oldCls!=""&&$oldTitle!="")
   {

      $dbFile=getData($oldTitle,$oldCls)[0];
  }
  else
  {
      $dbFile=getData($title,$cls)[0];
  }



  if($changFlag=="yes"&&$dbFile!=false)
  {   
      $dbFile=array_filter(explode(",",str_replace(" ", "", $dbFile["fileName"])));
      foreach($dbFile as $v)
      {
        
        if(in_array($v,$fileList))
        {
            $newFiles=$newFiles.$v.",";
        }
        else
        {
            if (file_exists($filePath.$v)) 
            {
               unlink($filePath.$v);
            }
       }
   }
   $newFiles=substr($newFiles, 0,-1);

  //如果标题和类没有修改就直接进行内容修改
   if($oldCls==$cls&&$oldTitle==$title)
   {
     file_put_contents($txtPath.$cls."#-#".$title.".txt",$data);
     update(array("fileName"=>$newFiles),$title,$cls,);
     return  "saveOk";
    }
    else
    {

        if(file_exists($txtPath.$oldCls."#-#".$oldTitle.".txt"))
        {
            rename($txtPath.$oldCls."#-#".$oldTitle.".txt", $txtPath.$cls."#-#".$title.".txt");
        }
        update(array("cls"=>$cls,"title"=>$title,"fileName"=>$newFiles),$oldTitle,$oldCls);
        file_put_contents($txtPath.$cls."#-#".$title.".txt",$data);
        return  "saveOk";
    }

}
  //不论有没有只要是导入都要修改文本
else if($changFlag=="no"&&$dbFile==false)
{
   file_put_contents($txtPath.$cls."#-#".$title.".txt",$data);
     //如果没有就在数据库中添加数据
   if($dbFile==false)
   {
      insert(array("cls"=>$cls,"title"=>$title,"fileName"=>""));
  }
  return  "saveOk";

}
else if($changFlag=="no"&&$dbFile!=false&&$noCheckSave=="yes")
{
  file_put_contents($txtPath.$cls."#-#".$title.".txt",$data);
  return  "saveOk";
}
else if($changFlag=="no"&&$dbFile!=false&&$noCheckSave=="no")
{  
    return  "enterButHavedFile";
}
else if($changFlag=="yes"&&$dbFile==false)
{
    return  "changButNoFile";
}

}




//插入数据库函数
function  insert($dic,$table="dataB")
{
   global $db;
   $str="INSERT INTO  ".$table." (";
       $name="";
       $value="";
       if(is_array($dic))
       {  
          foreach($dic as $k=>$v) 
          {
             $name=$name.$k.",";
             $value=$value.":".$k.",";
         }

         $name=substr($name,0,-1);
         $value=substr($value,0,-1);
         $str=$str.$name.") VALUES (".$value.")";
         $pre=$db->prepare($str);

         foreach($dic as $k=>$v) 
         {
             if($v==null)
             {
                $v="";
            }
            $pre->bindValue(":".$k,$v,SQLITE3_TEXT);
        }
        $result= $pre->execute();

        if($result)
        {
         return "insertOK";
     }
 }
 else
 {

  return  "insertFaile";
}

}


//删除数据库数据
function deleData($title,$cls,$table="dataB")
{
  global $db,$txtPath;
  $pre=$db->prepare("delete from ".$table." where (title='".$title."' and cls='".$cls."')");
  
  $result=$pre->execute();
  if($result)
  {
    if(file_exists($txtPath.$cls."#-#".$title.".txt")) 
    {
        unlink($txtPath.$cls."#-#".$title.".txt");
    }
    return "删除成功";
}
return "删除失败";
}


//修改数据库
function update($dic,$title,$cls="",$table="dataB")
{
 global $db;
 $str="update  ".$table." set ";
 foreach($dic as $k=>$v)
 {
   $str=$str.$k."=".":".$k.",";

}
$str=substr($str, 0,-1)." where (cls='".$cls."' and  title='".$title."')";
$pre=$db->prepare($str);

foreach($dic as $k=>$v)
{
  $pre->bindValue(":".$k,$v,SQLITE3_TEXT);
}

$result=$pre->execute();

if($result) 
{
  $affectedRows = $db->changes();
  if ($affectedRows > 0) 
  {
     return  "updateOK";
 }
 else
 {
     "updateFaile";
 }
}
else
{
   "updateFaile";
}
}

//查找数据库数据
function getData($title="",$cls="",$table="dataB")
{
   global $db;

   if($title!=""&&$cls=="")
   {

      $pre=$db->prepare("select * from ".$table."  where  title  like:".$title);
      $pre->bindValue(":".$title,$title,SQLITE3_TEXT);
  }
  else if($title!="" &&$cls!="")
  {    
     
      $pre=$db->prepare("select * from ".$table."  where  (title='".$title."'  and cls='" .$cls."')");

  }
  else if($title==""&&$cls!="")
  {
      $pre=$db->prepare("select * from ".$table."  where    cls='" .$cls."'");

  }
  else
  {
      $pre=$db->prepare("select * from ".$table);
  }

  $result=$pre->execute();

  $t=[];
  while($row=$result->fetchArray(SQLITE3_ASSOC))
  {
      $t[]=$row;
  }
 // echo json_encode($t);

  return $t;
}



//创造表格
function createTable($str)
{
   global $db;
   $db->exec($str);
}

// echo  createTable("create table if not exists dataB (id integer primary key,title text not null,fileName text not null,time timestamp default current_timestamp)");


//文件上传
function upload($formDate)
{  
    if($_SERVER['REQUEST_METHOD']=="POST"&&isset($_FILES['data']))
    {
        $file=$_FILES['data'];
        $fileName=trim(basename($file["name"]));
        $year = date('Y');     // 4位年份，如：2023
        $month = date('m');    // 2位月份，如：01-12
        $day = date('d');      // 2位日期，如：01-31
        $hour = date('H');     // 24小时制，如：00-23
        $minute = date('i');   // 分钟，如：00-59
        $second = date('s');   // 秒，如：00-59
        // 组合成完整时间字符串
        $newName=$year.$month.$day.$hour.$minute.$second."-".$formDate["cls"]."-".$formDate["title"]."-".$fileName;

        $txtPath="../../datas/file/".$newName;
        $dbFileName=getData($formDate["title"],$formDate["cls"])[0];
        $cls=$formDate["cls"];
        $changFlag=$formDate["changFlag"];
  
        if($changFlag=="no"&&$dbFileName==false)
        {  
         
            insert(array("cls"=>$formDate["cls"],"title"=>$formDate["title"],"fileName"=>$newName));
        }
        // 在上传前必须保存一次文件了，所有这里没有必要了
        else if($changFlag=="no"&&$dbFileName!=false)
        {   
            return "数据库中已有文件".$formDate["cls"]."#-#".$formDate["title"];
        }
        else if($changFlag=="yes"&&$dbFileName!=false)
        // else if($dbFileName!=false)
        {
         $dbFileName=array_filter(explode(",",str_replace(" ", "", $dbFileName["fileName"])));

         if(!in_array($newName,$dbFileName))
         {
            $value=implode(",",$dbFileName).",".$newName;
            update(array("fileName"=>$value),$formDate["title"],$formDate["cls"]);
        }
    }
    else
    {
       return "数据库中没有文件".$formDate["cls"]."#-#".$formDate["title"];
   }

   if(move_uploaded_file($file["tmp_name"], $txtPath))
   {
   //这里一定要是名字
     return  $newName;
 }
}
return  "uplaodFaile";
} 



//模糊查找文件
function findFile($str,$table="dataB")
{
   global $db;
   $pre=$db->prepare("select * from  ".$table." where (title like '%".$str."%'  or  cls  like  '%".$str."%' )");
   $result=$pre->execute();
   $dic=[];
   while($row=$result->fetchArray(SQLITE3_ASSOC))
   {
      $dic[]=$row;
  }
  return json_encode($dic,true);
}


//点击工具栏中的类进行显示名称
function showAllTitle($cls)
{
  $dic=getData("",$cls);
  return json_encode($dic,true);
}

//显示靠前面的类和名称数据
function getToolCls($count)
{
   global $db;
   $pre=$db->prepare("select cls,title, count(*) as c from dataB group by cls order by c desc limit ".$count);
   $result=$pre->execute();
   $dic=[];
   while($row=$result->fetchArray(SQLITE3_ASSOC))
   {
      $dic[]=$row;
  }
  return json_encode($dic,true);
}

//排序靠前的前面所有数据
function getInitData($count)
{
   global $db;
   $pre=$db->prepare("select * from dataB  where cls in (select cls  from dataB group by cls order by count(cls) desc limit ".$count.")");
   $result=$pre->execute();
   $dic=[];
   while($row=$result->fetchArray(SQLITE3_ASSOC))
   {
      $dic[]=$row;
  }
  return json_encode($dic,true);
}

//获得所有的类
function getAllCls()
{
   global $db;
   $pre=$db->prepare("select cls from dataB group by cls order by id");
   $result=$pre->execute();
   $dic=[];
   $ndic=[];
   while($row=$result->fetchArray(SQLITE3_ASSOC))
   {
      $dic[]=$row;
  }
  return json_encode($dic,true);
}
?>
